package torrent;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Timer;
import java.util.TimerTask;
import library.QueryString;

public class Peer extends TimerTask {

  public String fileName, query, url, response;
  int port, uploaded, downloaded, left;

  public static void main(String[] Args) {
    Peer cl = new Peer(new File("haha.torrent"));
//    Writer w;
//    //InputStream in = new InputStream();
//    //Reader r = new new InputStreamReader(in);
//    cl.sendGetRequest("http://localhost:5000", cl.query);

  }

  public Peer() {
    fileName = "";
    port = 0;
    uploaded = 0;
    downloaded = 0;
    left = 0;
  }

  public Peer(File f) {
    try {
      BufferedReader br = new BufferedReader(new FileReader(f));
      url = br.readLine();
      String[] type = url.split(":");
      port = Integer.parseInt(type[2]);
      fileName = "";

      MessageDigest md;
      md = MessageDigest.getInstance("SHA-1");
      byte[] data = f.getName().getBytes("UTF-8");
      md.update(data);
      data = md.digest();
      StringBuilder sb = new StringBuilder();
      for (int x = 0; x < data.length; x++) {
        sb.append((char) data[x]);
      }
      fileName = sb.toString();
      
      QueryString qs = new QueryString("file_name", fileName);
      qs.add("port", Integer.toString(port));
      qs.add("uploaded", "15");
      qs.add("downloaded", "20");
      qs.add("left", "10");
      query = qs.toString();
    } catch ( NoSuchAlgorithmException |  IOException e ) {
      System.out.println(e);
    }

    

  }

  public String sendGetRequest(String endpoint, String requestParameters) {
    String result = null;
//if (endpoint.startsWith("http://"))
//{
// Send a GET request to the servlet
    try {
// Construct data
      StringBuilder data = new StringBuilder();

// Send data
      String urlStr = endpoint;
      if (requestParameters != null && requestParameters.length() > 0) {
        urlStr += "?" + requestParameters;
      }
      URL urlcon = new URL(urlStr);
      URLConnection conn = urlcon.openConnection();
      conn.connect();
      StringBuilder sb;
      try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
        sb = new StringBuilder();
        String line;
        while (!rd.ready()) {
          System.out.println("not ready!!");
        }
        response = rd.readLine();
        System.out.println(response);
      }
      result = sb.toString();
    } catch (Exception e) {
      System.out.println(e);
    }
//}
    return result;
  }

  public static void postData(Reader data, URL endpoint, Writer output) throws Exception {
    HttpURLConnection urlc = null;
    try {
      urlc = (HttpURLConnection) endpoint.openConnection();
      try {
        urlc.setRequestMethod("POST");
      } catch (ProtocolException e) {
        throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
      }
      urlc.setDoOutput(true);
      urlc.setDoInput(true);
      urlc.setUseCaches(false);
      urlc.setAllowUserInteraction(false);
      urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");

      OutputStream out = urlc.getOutputStream();

      try {
        try (Writer writer = new OutputStreamWriter(out, "UTF-8")) {
          pipe(data, writer);
        }
      } catch (IOException e) {
        throw new Exception("IOException while posting data", e);
      } finally {
        if (out != null) {
          out.close();
        }
      }

      InputStream in = urlc.getInputStream();
      try {
        try (Reader reader = new InputStreamReader(in)) {
          pipe(reader, output);
        }
      } catch (IOException e) {
        throw new Exception("IOException while reading response", e);
      } finally {
        if (in != null) {
          in.close();
        }
      }

    } catch (IOException e) {
      throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
      if (urlc != null) {
        urlc.disconnect();
      }
    }
  }

  private static void pipe(Reader reader, Writer writer) throws IOException {
    char[] buf = new char[1024];
    int read = 0;
    while ((read = reader.read(buf)) >= 0) {
      writer.write(buf, 0, read);
    }
    writer.flush();
  }

  @Override
  public void run() {
    sendGetRequest(url, this.query);
  }
}
